package com.newlink.building.common_base.utils

import android.content.Context
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date


//使用HandlerThread在同一个线程中按顺序执行，避免多线程并发写入文件引发的问题
class LogHandlerThread private constructor() {

    companion object {
        @Volatile
        var instance: LogHandlerThread? = null
            // 获取单例实例
            get() {
                if (field == null) {
                    synchronized(LogHandlerThread::class.java) {
                        if (field == null) {
                            field = LogHandlerThread()
                        }
                    }
                }
                return field
            }
            private set

        const val LOG_FILENAME: String = "app_log.txt" // 日志文件名

        //        const val cacheFileSize: Int = 10 * 1024 * 1024
        const val cacheFileMegaSize: Double = 5.0 //缓存文件最大的MB值
    }

    private var handlerThread: HandlerThread? = null
    private var handler: Handler? = null

    // 停止HandlerThread，防止内存泄漏
    fun quit() {
        if (handlerThread != null) {
            handlerThread?.quitSafely()
            handlerThread = null
            handler = null
        }
    }

    init {
        initHanderThead()
    }

    fun initHanderThead() {
        if (handlerThread == null) {
            // 创建并启动HandlerThread
            handlerThread = HandlerThread("LogHandlerThread")
            handlerThread?.start()
            // 使用HandlerThread的Looper创建Handler
            handler = Handler(handlerThread!!.looper)
        }
    }

    // 保存日志到私有目录
    fun writeLog(context: Context, tag: String = "", message: String) {
        handler?.post {
            // 获取外部存储私有目录
            val externalDir = context.getExternalFilesDir(null)
                ?: // 外部存储不可用
                return@post
            val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
            val currentDate: String = sdf.format(Date())
            val logEntry = "$currentDate [$tag]: $message"
            // 定义日志文件名称
            val logFile = File(externalDir, LOG_FILENAME)

            var writer: FileWriter? = null
            try {
                // 打开文件写入流，append模式
                writer = FileWriter(logFile, true)
                writer.append(logEntry)
                writer.append("\n")
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                if (writer != null) {
                    try {
                        writer.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    fun appendLineBreak(context: Context, line: Int = 1) {
        handler?.post {
            val externalDir = context.getExternalFilesDir(null)
            val logFile = File(externalDir, LOG_FILENAME)

            var writer: FileWriter? = null
            try {
                // 打开文件写入流，append模式
                writer = FileWriter(logFile, true)
                for (i in 0 until line) {
                    writer.append("\n")
                }
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                if (writer != null) {
                    try {
                        writer.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    fun readLog(context: Context, callback: LogReadCallback) {
        handler?.post {
            val externalDir = context.getExternalFilesDir(null)

            val logFile = File(externalDir, LOG_FILENAME)
            if (!logFile.exists()) {
                logFile.createNewFile()
            }
            val logContent = StringBuilder()

            var character: Int
            val bufferedReader = BufferedReader(FileReader(logFile))
            try {
//                BufferedReader(FileReader(logFile)).use { reader ->
//                    var line: String?
//                    while ((reader.readLine().also { line = it }) != null) {
//                        logContent.append(line)
//                    }
//                }

                // 逐个字符读取
                while ((bufferedReader.read().also { character = it }) != -1) {
                    logContent.append(character.toChar()) // 每次读取一个字符，包括换行符
                }
                bufferedReader.close()

                callback.onFileRead(logContent.toString())
            } catch (e: IOException) {
                e.printStackTrace()
                bufferedReader.close()
            }
        }
    }

    // 超出大小,需要裁剪一半大小
    fun isNeedReSizeFile(context: Context) {
        val externalDir = context.getExternalFilesDir(null)
        val logFile = File(externalDir, LOG_FILENAME)
        val currentFileSize = getLogFileMegaSize(context)
        Log.d("[LogHandlerThread]", "isNeedResizeFile $currentFileSize - $cacheFileMegaSize")
        if (getLogFileMegaSize(context) >= cacheFileMegaSize) {
            deleteFirstHalfContent(logFile.absolutePath)
        }
    }

    fun deleteFirstHalfContent(filePath: String) {
        Log.d("[LogHandlerThread]", "deleteFirstHalfContent $filePath")
        handler?.post {
            val lines: MutableList<String> = ArrayList()

            // 读取文件的所有行
            try {
                BufferedReader(FileReader(filePath)).use { reader ->
                    var line: String? = null
                    while ((reader.readLine().also {
                            if (it != null) {
                                line = it
                            }
                        }) != null) {
                        line?.let {
                            if (it.isEmpty()) {
                                lines.add("\n")
                            } else {
                                lines.add(it)
                            }
                        }
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }

            // 计算文件总行数
            val totalLines = lines.size
            val halfIndex = totalLines / 2 // 前一半内容的结束行索引

            // 截取后一半的内容
            val secondHalf: List<String> = lines.subList(halfIndex, totalLines)

            // 将后一半内容写回文件
            try {
                BufferedWriter(FileWriter(filePath)).use { writer ->
                    for (line in secondHalf) {
                        if (line.isNotEmpty()) {
                            writer.write(line)
                            writer.newLine()
                        }
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

//    fun deleteFirstHalfContent2(inputFilePath: String) {
//        val totalLine = getTotalLine(inputFilePath)
//        var outputFilePath = "$inputFilePath.bak"
//
//        val inputFile = File(inputFilePath)
//        val outputFile = File(outputFilePath)
//        // 创建文件读取器
//        val reader = BufferedReader(FileReader(inputFile))
//        val writer = BufferedWriter(FileWriter(outputFile))
//
//        var line: String?
//        var lineNumber = 0
//
//
//        // 跳过前totalLine/2行
//        while (lineNumber < totalLine / 2 && (reader.readLine().also { line = it }) != null) {
//            lineNumber++
//        }
//
//        // 写入剩余的行
//        while ((reader.readLine().also { line = it }) != null) {
//            writer.write(line)
//            writer.newLine()
//        }
//        // 关闭资源
//        reader.close()
//        writer.close()
//
//        inputFile.delete()
//        outputFile.renameTo(inputFile)
//
//    }
//
//    fun getTotalLine(filePath: String): Int {
//        var lineCount = 0
//        try {
//            BufferedReader(FileReader(filePath)).use { reader ->
//                while (reader.readLine() != null) {
//                    lineCount++
//                }
//            }
//        } catch (e: IOException) {
//            e.printStackTrace()
//        }
//        return lineCount
//    }

    fun clearLog(context: Context) {
        handler?.post {
            val externalDir = context.getExternalFilesDir(null)
            externalDir.let {
                val logFile = File(externalDir, LOG_FILENAME)
                logFile.delete()
            }
        }
    }

    fun isLogFileEmpty(context: Context): Boolean {
        val externalDir = context.getExternalFilesDir(null)
        externalDir.let {
            val logFile = File(externalDir, LOG_FILENAME)
            if (!logFile.exists()) return true
            return logFile.length() == 0L
        }
        return false
    }

    fun getLogFileMegaSize(context: Context): Double {
        val externalDir = context.getExternalFilesDir(null)
        externalDir.let {
            val logFile = File(externalDir, LOG_FILENAME)
            return logFile.length().toDouble() / (1024 * 1024)
        }
        return 0.0
    }

    interface LogReadCallback {
        fun onFileRead(content: String?)
    }
}